package controller;

import com.itextpdf.text.pdf.PdfReader;

import constant.Constant;

import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;

import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;

import javafx.scene.control.TextField;

import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;

import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;

import utils.*;


import java.io.File;
import java.io.IOException;
import java.net.URL;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import static utils.MybatisUtils.getYanZheng;

public class MainFrameController implements Initializable {

    @FXML
    private MenuBar menuBar;
    @FXML
    private ComboBox t_zhuang_ding;
    @FXML
    private ComboBox t_lian_shu;
    @FXML
    private ComboBox t_yin_shua_fang_shi;
    @FXML
    private TextField t_pdf_path;

    @FXML
    private PasswordField t_company;
    @FXML
    private TextField t_model;
    @FXML
    private TextField t_weight;
    @FXML
    private TextField t_material;
    @FXML
    private TextField t_page_count;
    @FXML
    private TextField t_num;
    @FXML
    private TextField t_width;
    @FXML
    private TextField t_height;
    @FXML
    private TextField t_row;
    @FXML
    private TextField t_col;
    @FXML
    private CheckBox cc;
    @FXML
    private CheckBox cm;
    @FXML
    private CheckBox cy;
    @FXML
    private CheckBox ck;
    @FXML
    private CheckBox left_text;
    @FXML
    private CheckBox right_text;
    @FXML
    private CheckBox top_text;
    @FXML
    private CheckBox bottom_text;
    @FXML
    private CheckBox alert_info;
    @FXML
    private CheckBox qiang_zhi_zheng_fan;
    @FXML
    private FlowPane zs_flowPane;
    private boolean isOn = false;//判断鼠标是否按过

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Constant.init();
        //新建一个菜单
        Menu about = new Menu();
        //新建一个标签
        Label label = new Label("关于");
        //给标签绑定鼠标点击事件
        label.setOnMouseClicked(event -> {
            ItextUtil.alertInfo("欢迎使用有宝贵意见可以一起交流一起完善\n只开发了竖版,横版慎用\n有问题可以再CPC论坛跟帖留言\n交流群:974164154","感谢使用 勿用于生产");
        });
        //将标签设置到menu的graphic属性当中
        about.setGraphic(label);
        menuBar.getMenus().add(about);

        t_zhuang_ding.getItems().setAll("骑马钉");
//        t_zhuang_ding.getItems().setAll("骑马钉", "胶装");
        t_zhuang_ding.getSelectionModel().select(0);

        t_lian_shu.getItems().setAll("单联", "双联", "三联", "四联", "五联", "六联", "七联", "八联");
//        t_lian_shu.getItems().setAll("单联", "双联");
//        t_lian_shu.getItems().setAll("单联");
        t_lian_shu.getSelectionModel().select(0);

        t_yin_shua_fang_shi.getItems().setAll("优先正反版", "全部自翻");
        t_yin_shua_fang_shi.getSelectionModel().select(0);

        t_pdf_path.setText("支持双击打开 拖拽");
        //让 t_pdf_path 可以支持拖拽
        t_paf_path_action();
        t_pdf_path.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                if (event.getClickCount() == 2) {
                    OpenFile();
                }

            }
        });
        cc.setSelected(Constant.is_cc);
        cm.setSelected(Constant.is_cm);
        cy.setSelected(Constant.is_cy);
        ck.setSelected(Constant.is_ck);
        left_text.setSelected(Constant.is_left_text);
        right_text.setSelected(Constant.is_right_text);
        top_text.setSelected(Constant.is_top_text);
        bottom_text.setSelected(Constant.is_bottom_text);
    }

    private void t_paf_path_action() {
        t_pdf_path.setOnDragOver(new EventHandler<DragEvent>() {
            @Override
            public void handle(DragEvent event) {
                if (event.getGestureSource() != t_pdf_path) {
                    event.acceptTransferModes(TransferMode.ANY);
                }
            }
        });
        t_pdf_path.setOnDragDropped(new EventHandler<DragEvent>() {
            @Override
            public void handle(DragEvent event) {
                Dragboard dragboard = event.getDragboard();
                if (dragboard.hasFiles()) {
                    try {
                        File file = dragboard.getFiles().get(0);
                        if (file != null && file.getName().toLowerCase().indexOf(".pdf") != -1) {
                            t_pdf_path.setText(file.getAbsolutePath());
//                            t_company.setText("北大青鸟");
                            setText(file);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void setText(File file) {
        String name = file.getName();
        PdfReader reader = null;
        try {

            t_model.setText(NameUtils.getModel(name));


            t_weight.setText(NameUtils.getWeight(name) + "");


            t_material.setText(NameUtils.getMaterial(name));

            reader = new PdfReader(file.toString());

            t_page_count.setText(reader.getNumberOfPages() + "");


            t_num.setText(NameUtils.getNumber(name));

            java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");

            try {
                float pt = 72.0f / 25.4f;
                t_width.setText(df.format(reader.getBoxSize(1, "trim").getWidth() / pt));
                t_height.setText(df.format(reader.getBoxSize(1, "trim").getHeight() / pt));
                Constant.chuxue = (reader.getBoxSize(1, "media").getWidth() / pt - reader.getBoxSize(1, "trim").getWidth() / pt) / 2;
                if (name.indexOf("骑马钉") != -1) {
                    t_zhuang_ding.getSelectionModel().select(0);
                } else if (name.indexOf("胶装") != -1) {
                    t_zhuang_ding.getSelectionModel().select(1);
                }
            } catch (Exception e) {
                ItextUtil.alert("文件请做好出血!", Constant.titile);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

    }

    @FXML
    protected void action(Event event) {
        MenuItem item = (MenuItem) event.getTarget();
        String msg = item.getText();

        if (msg.equals("标记")) {
            InUtils.peiZhi("");
        }else if(msg.equals("文件名读取规则")){
            InUtils.wenjianmingduquguizhe("");
        }
        System.out.println(123);


    }

    public void OpenFile() {
        File file_parent = null;
        if (new File(Constant.open_file_parent).exists()) {
            List<String> list = ReadAndWriteFile.readtFile(Constant.open_file_parent, "utf8");
            if (list != null && list.size() > 0) {
                file_parent = new File(list.get(0));
            }
        }

        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("打开PDF");
        if (file_parent != null) {
            fileChooser.setInitialDirectory(file_parent);
        }
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PDF Files", "*.pdf"), new FileChooser.ExtensionFilter("All Files", "*.*"));
        File file = fileChooser.showOpenDialog(Constant.primaryStage);
        if (file != null) {
            String parent = file.getParent();
            ReadAndWriteFile.writeInFile(Constant.open_file_parent, parent, "utf8");
            t_pdf_path.setText(file.toString());
            setText(file);

        }
    }

    public void work(ActionEvent actionEvent) {
        if(!Constant.active){
            if(!t_company.getText().equals(getYanZheng())){
                ItextUtil.alert("验证码错误!\n请联系群主或管理\nQQ群974164154",Constant.titile);
                return;
            }
        }

        Constant.init();
        List<String> list_pt = new ArrayList<>();
        ObservableList<Node> children = zs_flowPane.getChildren();
        for (Node child : children) {
            ObservableList<Node> children1 = ((FlowPane) child).getChildren();
            if(children1.size()==11){
                StringBuilder stringBuilder = new StringBuilder();
                for (Node node : children1) {

                    if(node instanceof TextField){
                        TextField textField1 = (TextField)node;
                        stringBuilder.append(textField1.getText()+",");
                    }

                }
                list_pt.add(stringBuilder.toString());
            }
        }
        System.out.println("生成开始");

        String company = "";
        String model = t_model.getText();
        int weight = Integer.valueOf(t_weight.getText());
        String material = t_material.getText();
        int num = 0;
        if(!t_num.getText().equals("")){
            num = Integer.valueOf(t_num.getText());
        }

        int pageCount = Integer.valueOf(t_page_count.getText());
        float width = Float.valueOf(t_width.getText());
        float height = Float.valueOf(t_height.getText());
        int col = Integer.valueOf(t_col.getText());
        int row = Integer.valueOf(t_row.getText());
        String binding = (String) (t_zhuang_ding).getSelectionModel().getSelectedItem();
        String lian = (String) (t_lian_shu).getSelectionModel().getSelectedItem();

        String pinbanfangshi = (String) (t_yin_shua_fang_shi).getSelectionModel().getSelectedItem();
        String path = t_pdf_path.getText();
        Info info = new Info();
        info.setCompany(company);
        info.setModel(model);
        info.setWeight(weight);
        info.setMaterial(material);
        info.setNum(num);
        info.setWidth(width);
        info.setPageCount(pageCount);
        info.setHeight(height);
        info.setCol(col);
        info.setRow(row);
        info.setBinding(binding);
        info.setLian(lian);
        info.setPath(path);
        if(false){
            if(col==4&&row==4&&lian.equals("单联")){
                ItextUtil.alert("联数:"+lian+",行列"+col+"x"+row+"\n不支持",Constant.titile);
                return;
            }else if(col>4&&row>4){
                ItextUtil.alert("联数:"+lian+",行列"+col+"x"+row+"\n不支持",Constant.titile);
                return;
            }else if(col%2==1){
                ItextUtil.alert("联数:"+lian+",行列"+col+"x"+row+"\n不支持",Constant.titile);
                return;
            }else if(binding.equals("胶装")&&(row==3)){
                ItextUtil.alert("联数:"+lian+",行列"+col+"x"+row+"\n不支持",Constant.titile);
                return;
            }else if(binding.equals("骑马钉")&&pageCount%4!=0){
                ItextUtil.alert("装订方式:"+lian+",页数不能整除4"+"\n不支持",Constant.titile);
                return;
            }else if(pinbanfangshi.equals("全部自翻")){
                if(width*col<height*row){
                    ItextUtil.alert("自翻拼版宽度大于拼版高度"+"\n不支持",Constant.titile);
                    return;
                }
            }else if(width>height) {
                ItextUtil.alert("横版说明书,作者未曾考虑其中.结果大概率是错的,请仔细检查.", "友情提示");
                Constant.hengban = true;
            }else if(col==4&&row==3&&pinbanfangshi.equals("优先正反版")){
                ItextUtil.alert("印刷方式:"+pinbanfangshi+",行列"+col+"x"+row+"\n不支持\n把拼版改成全部自翻就支持了",Constant.titile);
                return;
            }
        }


        if (pinbanfangshi.equals("优先正反版")) {
            info.setPinbanfangshi(Constant.yin_shua_fang_shi_zheng_fan);
        } else {
            info.setPinbanfangshi(Constant.yin_shua_fang_shi_zi_fan);
        }

        if (lian.equals("单联")) {
            info.setLianshu(1);
        } else if (lian.equals("双联")) {
            info.setLianshu(2);
        } else if (lian.equals("三联")) {
            info.setLianshu(3);
        } else if (lian.equals("四联")) {
            info.setLianshu(4);
        } else if (lian.equals("五联")) {
            info.setLianshu(5);
        } else if (lian.equals("六联")) {
            info.setLianshu(6);
        } else if (lian.equals("七联")) {
            info.setLianshu(7);
        } else if (lian.equals("八联")) {
            info.setLianshu(8);
        } else if (lian.equals("九联")) {
            info.setLianshu(9);
        }
        info.setSpace(Constant.space);
        info.setJx(Constant.jiao_xian_chang_du);
        info.setJj(Constant.jiao_xian_ju_bian);
        info.setPt_list(list_pt);
        Constant.pdf_path = info.getPath();

        InUtils.createPdfByInfo(info);

        // Constant.showMessage("你在就好了","傻大姐爱斯达克两节课拿手机雷吉纳开始了卡死 傻大姐拉克丝就能看啥叫拉伸傻大姐爱斯达克两节课拿手机雷吉纳开始了卡死 傻大姐拉克丝就能看啥叫拉伸");

    }


    public void updatePeiZi(MouseEvent mouseEvent) {
        StringBuilder stringBuilder = new StringBuilder();
        //脚线长度=3
        //脚线距边=3
        //脚线粗细=0.1
        //间距=4
        stringBuilder.append("\r\n");
        stringBuilder.append("脚线长度=" + Constant.jiao_xian_chang_du + "\r\n");
        stringBuilder.append("脚线距边=" + Constant.jiao_xian_ju_bian + "\r\n");
        stringBuilder.append("脚线粗细=" + Constant.jiao_xian_cu_xi + "\r\n");
        stringBuilder.append("间距=" + Constant.space + "\r\n");
        stringBuilder.append("C=" + cc.isSelected() + "\r\n");
        stringBuilder.append("M=" + cm.isSelected() + "\r\n");
        stringBuilder.append("Y=" + cy.isSelected() + "\r\n");
        stringBuilder.append("K=" + ck.isSelected() + "\r\n");
        stringBuilder.append("左=" + left_text.isSelected() + "\r\n");
        stringBuilder.append("右=" + right_text.isSelected() + "\r\n");
        stringBuilder.append("上=" + top_text.isSelected() + "\r\n");
        stringBuilder.append("下=" + bottom_text.isSelected() + "\r\n");
        ReadAndWriteFile.writeInFile(Constant.file_canshu, stringBuilder.toString(), "utf8");
        Constant.alert_info = alert_info.isSelected();
        Constant.qiang_zhi_zheng_fan = qiang_zhi_zheng_fan.isSelected();
        Constant.init();

    }

    public void add(ActionEvent actionEvent) {
//                      <FlowPane fx:id="zs_flowPane">
//                    <TextField prefWidth="120"/>
//                    <TextField prefWidth="30"/>
//                    <TextField prefWidth="30"/>
//                    <TextField prefWidth="30"/>
//                    <TextField prefWidth="30"/>
//                </FlowPane>
        int fontSize =9;
        int fontSizei = 10;
        FlowPane flowPane = new FlowPane();
        flowPane.setStyle("-fx-hgap: 6px");
        Label label = new Label("专");
        TextField textField = new TextField();
        textField.setPrefWidth(70);
        textField.setFont(new Font(fontSize));
        Label cl = new Label("C");
        TextField ct = new TextField();
        ct.setFont(new Font(fontSizei));
        ct.setPrefWidth(30);
        Label ml = new Label("M");
        TextField mt = new TextField();
        mt.setPrefWidth(30);
        mt.setFont(new Font(fontSizei));
        Label yl = new Label("Y");
        TextField yt = new TextField();
        yt.setPrefWidth(30);
        yt.setFont(new Font(fontSizei));
        Label kl = new Label("k");
        TextField kt = new TextField();
        kt.setPrefWidth(30);
        kt.setFont(new Font(fontSizei));
        Button b = new Button("删"+(Constant.add_count+1));
        b.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                ObservableList<Node> children = zs_flowPane.getChildren();
                int index =0;
                for (Node child : children) {
                    ObservableList<Node> children1 = ((FlowPane) child).getChildren();
                    boolean flag = false;
                    if(children1.size()==11){
                        for (int i = 0; i < children1.size(); i++) {
                            Node node = children1.get(i);
                            if(node instanceof Button){
                                Button button = (Button)node;
                                if(button.getText().equals(b.getText())){
                                    children.remove(index,index+1);
                                    Constant.height -= 25;
                                    Constant.primaryStage.setHeight(Constant.height);
                                    flag = true;
                                    break;
                                }
                            }
                        }
                    }
                    if(flag)break;
                    index++;
                }
            }
        });
        flowPane.getChildren().addAll(label, textField,cl,ct,ml,mt,yl,yt,kl,kt,b);
        zs_flowPane.getChildren().add(flowPane);


        if(Constant.add_count==0){
            Constant.height += 50;
        }else{
            Constant.height += 25;
        }
        Constant.add_count++;

        Constant.primaryStage.setHeight(Constant.height);
    }
}
